import {
  GraphQLString,
  GraphQLNonNull,
} from 'graphql';
import { createJwtToken } from '../utils/CreateJwtToken';
import { User } from '../../models';
import UserType from '../../types/UserType';
import { mutationWithClientMutationId } from "graphql-relay";

const CreateTokenMutation = mutationWithClientMutationId({
  name: 'createToken',
  inputFields: {
    name: { type: new GraphQLNonNull(GraphQLString) },
    password: { type: new GraphQLNonNull(GraphQLString) },
  },
  outputFields: {
    token: {
      type: GraphQLString,
      resolve: ({ token }) => token,
    },
    error: {
      type: GraphQLString,
      resolve: ({ error }) => error,
    },
    viewer: {
      type: UserType,
      resolve: ({ user }) => user,
    }
  },
  mutateAndGetPayload: async ({ name, password }) => {
    const user = await User.findOne({
      where: {
        name,
      },
    });
    if (!user) {
      return {
        error: '用户不存在',
      };
    }
    if (password !== user.password){
      return {
        error: '密码不正确',
        user,
      };
    }
    return {
      token: await createJwtToken(user.id),
      user,
    }
  }
});

export default CreateTokenMutation;
